package com.longteng.testng;

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Splitter;
import com.longteng.testng.annotation.Suffix;
import com.longteng.testng.annotation.SuffixHandler;
import com.longteng.testng.param.IGenerator;
import com.longteng.testng.param.Pair;
import com.longteng.testng.param.Row;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.List;

/**
 * Created by sky on 15-12-24
 */
@SuffixHandler("txt")
public class TxtGenerator implements IGenerator{

    @Override
    public List<Row> generate(Method method) {
        if(method.isAnnotationPresent(Suffix.class)){
            String path = method.getAnnotation(Suffix.class).target();
            try {
                File file = getFile(path);
                if(file==null){
                    throw new Exception("未发现文件:"+path);
                }
                List<String> lines = IOUtils.readLines(new FileInputStream(file));
                if(lines==null||lines.size()<2){
                    return Lists.newArrayList();
                }else{
                    List<Row> rows = Lists.newArrayList();
                    List<String> headers = Splitter.on("|").splitToList(lines.get(0));
                    for(int i=1;i<lines.size();i++){
                        List<String> params = Splitter.on("|").splitToList(lines.get(i));
                        Row row = new Row();
                        for(int j=0;j<headers.size();j++){
                            Pair pair = new Pair(headers.get(j),params.get(j));
                            row.addPair(pair);
                        }
                        rows.add(row);
                    }
                    return rows;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        throw new RuntimeException("方法必须含有suffix注解指定target");
    }

    private File getFile(String path){
        if(StringUtils.startsWith(path,"classpath:")){
            String f = StringUtils.substring(path,"classpath:".length());
            URL url = getClass().getClassLoader().getResource(f);
            if (url != null) {
                return new File(url.getPath());
            }
            return null;
        }
        return new File(path);
    }
}
